package com.lsh.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ：LiuShihao
 * @date ：Created in 2020/11/11 10:38 上午
 * @desc ：自定义 CustomAuthenticationFailureHandler 类来实现 AuthenticationFailureHandler 接口，用来处理认证失败后逻辑
 * onAuthenticationFailure()方法的第三个参数 exception 为认证失败所产生的异常，这里也是简单的返回到前台。
 */
@Slf4j
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
//    @Autowired
//    private ObjectMapper objectMapper;
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        log.info("登陆失败");

        httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        //httpServletResponse.getWriter().write(objectMapper.writeValueAsString(e.getMessage()));
        //认证失败重新跳转的登录页面
        httpServletResponse.sendRedirect("/login");
    }
}
